import { Hono } from 'hono';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
import { AppDataSource, CrawlerTask, TaskStatus, CrawlerEngine, TaskPriority } from '@weubi/shared';
import { TaskController } from '../controllers/TaskController';

export const taskRoutes = new Hono();
const taskController = new TaskController();

// 验证模式
const createTaskSchema = z.object({
  name: z.string().min(1).max(255),
  url: z.string().url(),
  description: z.string().optional(),
  engine: z.enum(['puppeteer', 'playwright', 'http', 'selenium']),
  priority: z.enum(['low', 'normal', 'high', 'urgent']).default('normal'),
  config: z.object({
    timeout: z.number().min(1000).max(300000).optional(),
    retries: z.number().min(0).max(10).optional(),
    delay: z.number().min(0).optional(),
    userAgent: z.string().optional(),
    headers: z.record(z.string()).optional(),
    headless: z.boolean().optional(),
    viewport: z.object({
      width: z.number(),
      height: z.number(),
    }).optional(),
    selectors: z.record(z.union([z.string(), z.object({
      selector: z.string(),
      attribute: z.string().optional(),
      transform: z.string().optional(),
      multiple: z.boolean().optional(),
    })])).optional(),
    script: z.string().optional(),
    schedule: z.string().optional(),
  }).optional(),
});

const updateTaskSchema = createTaskSchema.partial();

const querySchema = z.object({
  page: z.string().transform(Number).default('1'),
  limit: z.string().transform(Number).default('20'),
  status: z.enum(['pending', 'running', 'completed', 'failed', 'paused', 'cancelled']).optional(),
  engine: z.enum(['puppeteer', 'playwright', 'http', 'selenium']).optional(),
  priority: z.enum(['low', 'normal', 'high', 'urgent']).optional(),
  search: z.string().optional(),
});

// 获取任务列表
taskRoutes.get('/', zValidator('query', querySchema), async (c) => {
  try {
    const query = c.req.valid('query');
    const result = await taskController.getTasks(query);
    return c.json(result);
  } catch (error) {
    console.error('Get tasks error:', error);
    return c.json({
      success: false,
      error: 'Failed to fetch tasks',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 创建任务
taskRoutes.post('/', zValidator('json', createTaskSchema), async (c) => {
  try {
    const data = c.req.valid('json');
    const task = await taskController.createTask(data);
    return c.json({
      success: true,
      data: task,
      message: 'Task created successfully',
    }, 201);
  } catch (error) {
    console.error('Create task error:', error);
    return c.json({
      success: false,
      error: 'Failed to create task',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 获取单个任务
taskRoutes.get('/:id', async (c) => {
  try {
    const id = c.req.param('id');
    const task = await taskController.getTaskById(id);
    
    if (!task) {
      return c.json({
        success: false,
        error: 'Task not found',
      }, 404);
    }
    
    return c.json({
      success: true,
      data: task,
    });
  } catch (error) {
    console.error('Get task error:', error);
    return c.json({
      success: false,
      error: 'Failed to fetch task',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 更新任务
taskRoutes.put('/:id', zValidator('json', updateTaskSchema), async (c) => {
  try {
    const id = c.req.param('id');
    const data = c.req.valid('json');
    const task = await taskController.updateTask(id, data);
    
    if (!task) {
      return c.json({
        success: false,
        error: 'Task not found',
      }, 404);
    }
    
    return c.json({
      success: true,
      data: task,
      message: 'Task updated successfully',
    });
  } catch (error) {
    console.error('Update task error:', error);
    return c.json({
      success: false,
      error: 'Failed to update task',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 删除任务
taskRoutes.delete('/:id', async (c) => {
  try {
    const id = c.req.param('id');
    const success = await taskController.deleteTask(id);
    
    if (!success) {
      return c.json({
        success: false,
        error: 'Task not found',
      }, 404);
    }
    
    return c.json({
      success: true,
      message: 'Task deleted successfully',
    });
  } catch (error) {
    console.error('Delete task error:', error);
    return c.json({
      success: false,
      error: 'Failed to delete task',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 执行任务
taskRoutes.post('/:id/run', async (c) => {
  try {
    const id = c.req.param('id');
    const result = await taskController.runTask(id);
    
    return c.json({
      success: true,
      data: result,
      message: 'Task execution started',
    });
  } catch (error) {
    console.error('Run task error:', error);
    return c.json({
      success: false,
      error: 'Failed to run task',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 暂停任务
taskRoutes.post('/:id/pause', async (c) => {
  try {
    const id = c.req.param('id');
    const task = await taskController.pauseTask(id);
    
    if (!task) {
      return c.json({
        success: false,
        error: 'Task not found',
      }, 404);
    }
    
    return c.json({
      success: true,
      data: task,
      message: 'Task paused successfully',
    });
  } catch (error) {
    console.error('Pause task error:', error);
    return c.json({
      success: false,
      error: 'Failed to pause task',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 恢复任务
taskRoutes.post('/:id/resume', async (c) => {
  try {
    const id = c.req.param('id');
    const task = await taskController.resumeTask(id);
    
    if (!task) {
      return c.json({
        success: false,
        error: 'Task not found',
      }, 404);
    }
    
    return c.json({
      success: true,
      data: task,
      message: 'Task resumed successfully',
    });
  } catch (error) {
    console.error('Resume task error:', error);
    return c.json({
      success: false,
      error: 'Failed to resume task',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 取消任务
taskRoutes.post('/:id/cancel', async (c) => {
  try {
    const id = c.req.param('id');
    const task = await taskController.cancelTask(id);
    
    if (!task) {
      return c.json({
        success: false,
        error: 'Task not found',
      }, 404);
    }
    
    return c.json({
      success: true,
      data: task,
      message: 'Task cancelled successfully',
    });
  } catch (error) {
    console.error('Cancel task error:', error);
    return c.json({
      success: false,
      error: 'Failed to cancel task',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});

// 获取任务统计
taskRoutes.get('/stats/overview', async (c) => {
  try {
    const stats = await taskController.getTaskStats();
    return c.json({
      success: true,
      data: stats,
    });
  } catch (error) {
    console.error('Get task stats error:', error);
    return c.json({
      success: false,
      error: 'Failed to fetch task statistics',
      message: error instanceof Error ? error.message : 'Unknown error',
    }, 500);
  }
});
